using System;
using System.Net;
using System.Threading;
using CloudStorage.API.Exceptions;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using Rhino.Mocks;
using CloudStorage.API.Messages;
using CloudStorage.API.Messages.Extensions;

namespace CloudStorage.Tests.API.Messages.Extensions
{
	[TestClass]
	public class IMessageQueueDataContextExtensionsTests
	{
		[TestMethod, ExpectedException(typeof(ArgumentNullException))]
		public void QueueExists_expects_queueName()
		{
			var messageDataContext = MockRepository.GenerateMock<IMessageQueueDataContext>();
			messageDataContext.QueueExists(null);
		}

		[TestMethod, ExpectedException(typeof(ArgumentNullException))]
		public void QueueExists_expects_non_empty_queueName()
		{
			var messageDataContext = MockRepository.GenerateMock<IMessageQueueDataContext>();
			messageDataContext.QueueExists(string.Empty);
		}

		[TestMethod, ExpectedException(typeof(AbandonedMutexException))]
		public void QueueExists_throws_unknown_errors()
		{
			var messageDataContext = MockRepository.GenerateMock<IMessageQueueDataContext>();
			messageDataContext.Expect(mdc => mdc.GetQueueMetadata())
												.Throw(new AbandonedMutexException());

			messageDataContext.QueueExists("foo");
		}

		[TestMethod, ExpectedException(typeof(CloudStorageException))]
		public void QueueExists_throws_on_CloudStorageException()
		{
			var messageDataContext = MockRepository.GenerateMock<IMessageQueueDataContext>();
			messageDataContext.Expect(mdc => mdc.GetQueueMetadata())
												.Throw(new CloudStorageException("Oh no", HttpStatusCode.Unused));

			messageDataContext.QueueExists("foo");
		}

		[TestMethod]
		public void QueueExists_returns_false_when_exception_is_HttpStatusCodeNoContent()
		{
			var messageDataContext = MockRepository.GenerateMock<IMessageQueueDataContext>();
			messageDataContext.Expect(mdc => mdc.GetQueueMetadata())
												.Throw(new CloudStorageException("Oh no", HttpStatusCode.NoContent));

			var exists = messageDataContext.QueueExists("foo");

			Assert.IsFalse(exists);
		}

		[TestMethod]
		public void QueueExists_returns_true_when_Metadata_exists()
		{
			var messageDataContext = MockRepository.GenerateMock<IMessageQueueDataContext>();
			messageDataContext.Expect(mdc => mdc.GetQueueMetadata())
												.Return(MockRepository.GenerateStub<IQueueMetadata>());

			var exists = messageDataContext.QueueExists("foo");

			Assert.IsTrue(exists);
			messageDataContext.VerifyAllExpectations();
		}
	}
}